<template>
	<view>
		<st-mc-framework :navTitle="ModuleTitle" @changeLevel="changeLevel" ref="framework"
			@AddModuleData_select='AddModuleData_select'>
			<template #content>
				<view class="content" style="width: 100%;height: 100%;">
					<view class="contentBox" style="flex: 1;">
						<view class="container">

							<u--form class="u_form" labelPosition="left" :model="baseFormData" ref="uForm">
								<u-row justify="space-between" gutter="20">
									<u-col span="4">
										<u-form-item labelWidth="auto" label="实测人员:">
											<u--input v-model="baseFormData.TestName" placeholder="自动带出实测人员" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="产品名称:" @click="openBaseScreen('产品')"
											required>
											<u--input v-model="baseFormData.ProductName" placeholder="请选择产品名称" readonly
												border="none" /></u--input>
											<u-icon slot="right" name="arrow-right"></u-icon>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="加料日期:">
											<u--input v-model="baseFormData.StartTime" placeholder="自动带出加料日期" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>

								</u-row>
								<u-row justify="start" gutter="20">
									<u-col span="4">
										<u-form-item labelWidth="auto" label="重复测重:" @click="AddTestAgainVal" required>
											<u--input v-model="baseFormData.TestAgainVal" placeholder="自动带出重复测重"
												readonly border="none"></u--input>
											<u-icon slot="right" name="arrow-right"></u-icon>
										</u-form-item>
									</u-col>
									<u-col span="4">

										<u-form-item labelWidth="auto" label="测试结果:">
											<u--input v-model="baseFormData.ResultVal" placeholder="自动带出测试结果" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>
								</u-row>
							</u--form>

						</view>
						<view class="table">
							<table>
								<tr>
									<th width="8%">操作</th>
									<th width="8%">序号</th>
									<th>原材料</th>
									<th>含水量标准(%)</th>
									<th>实测含水量</th>
									<th>备注</th>
									<th>测试结果</th>
								</tr>

								<tr v-for="(item, index) in tableData">
									<td class="sticky-col">
										<uni-icons type="trash" size="30" @click="trash(index)"></uni-icons>
									</td>
									<td>{{index + 1}}</td>
									<td @click="openBaseScreen('原材料', index)">
										<u--textarea v-model="item.ProductName" autoHeight border="none" disabled
											class="fixed-textarea"></u--textarea>
									</td>
									<td>
										<u--textarea v-model="item.TestStandardNUM" autoHeight border="none" disabled
											class="fixed-textarea"></u--textarea>
									</td>
									<td>
										<u--textarea v-model="item.TestingNUM" autoHeight border="none"
											@blur="handlerTestingNUM(item, index)" class="fixed-textarea"></u--textarea>
									</td>
									<td>
										<u--textarea v-model="item.Remark" autoHeight border="none"
											class="fixed-textarea"></u--textarea>
									</td>
									<td>
										<u--textarea v-model="item.TestresultVal" autoHeight border="none" disabled
											class="fixed-textarea"></u--textarea>
									</td>
								</tr>
							</table>

						</view>
					</view>

					<view class="DetailsbottomBtns">
						<button class="button1" block @click="submit">
							保&nbsp &nbsp 存
						</button>
					</view>
				</view>
			</template>

		</st-mc-framework>

		<u-toast ref="uToast"></u-toast>
		<u-modal :show="modalshow" :title="modaltitle" width="400" @confirm='modalconfirm' :showCancelButton='true'
			@cancel='modalshow=false'>
			<view class="slot-content">
				{{modalcontent}}
			</view>
		</u-modal>
		<u-action-sheet :actions="testAgainOptions" :show="testAgainShow" @select="testAgainClick"
			@close="testAgainShow=false"></u-action-sheet>
		<m-loading :text="loadingName" v-model="showMLoading" :showClose="false"
			maskBackgroundColor="rgba(0,0,0,0.3)"></m-loading>
	</view>
</template>

<script>
	import {
		getTimeStamp,
		getFormatDate,
		getFormatDateTime,
		getBefore7DateTime,
		formatDateTime,
		navigateMixin,
		baseAddModuleData_select,
		getchangeLevel
	} from '@/st_mes_zs/common/base.js';
	export default {
		mixins: [navigateMixin, baseAddModuleData_select],
		data() {
			return {
				testAgainShow: false, //重复测量筛选显示
				testAgainOptions: [{
						name: '是',
						id: 1,
						status: true
					},
					{
						name: '否',
						id: 0,
						status: false
					}
				], //重复测量筛选数组
				ButtonShow: true,
				showMLoading: false,
				loadingName: '正在加载中……',

				baseFormData: {
					ShiftName: '',
					ShiftID: null,
					TestAgainVal: '',
					TestAgain: '',
					TestName: '',
					EquipmentName: '',
					EquipmentID: '',
					ProductName: '',
					ProductID: 0,
					ProductCode: '',
					ProductSpec: '',
					WhiteORNight: null,
					StartTime: '',

					ApproveID: '',
					ResultVal: '',
					Result: null,
					Result: '',
					ProjectName: ''
				},

				tableData: [],
				tableDataIndex: null,
				modalshow: false,
				modaltitle: '',
				modalcontent: '',
				submitButton: '提交',
				submitButtonShow: true,
				MoludList: [],
				ProductNameselect: false, //第一次进来是否多个
				FWorkshopID: null, //模块id
				ModuleTitle: '', //标题
				TestresultList: [{
						name: '不合格',
						id: 0,
						status: false
					}, {
						name: '合格',
						id: 1,
						status: true
					},

				],
			};
		},
		onReady() {
			var that = this
			uni.hideLoading();
			const {
				GuyueModule,
				UserInfo,
				appConfigInfo
			} = that.$store.state;
			const {
				MesBasicInfo
			} = GuyueModule;
			that.FWorkshopID = MesBasicInfo.FWorkshopID;
			that.ModuleTitle = appConfigInfo.ActiveModule.ModuleName

			that.$nextTick(() => {
				setTimeout(() => {
					that.BtnShow = true;
				}, 500)
			})
		},
		onLoad(item) {
			var that = this
			uni.$on('refreshDetail', (res) => {
				that.getValue(res.data); // 调用目标方法
			});
			that.$safeStatus({
				payload: '其他', // 要传递的数据
			});
			const {
				GuyueModule,
				UserInfo,
				appConfigInfo
			} = that.$store.state;
			const {
				MesBasicInfo
			} = GuyueModule;
			// 统一处理加载状态
			const setLoading = (state) => that.showMLoading = state;
			// 主处理逻辑
			if (item.ZS_WaterContentID) {
				setLoading(true);
				that.queryList(item.ZS_WaterContentID);
				return;
			}
			// 统一处理表单默认值
			const formDefaults = {
				EquipmentID: MesBasicInfo.warehouse.EquipmentID,
				EquipmentName: MesBasicInfo.warehouse.EquipmentName,
				StartTime: getFormatDate(new Date()),
				TestName: UserInfo.EmplName,

				ShiftName: MesBasicInfo.ShiftObj.ShiftName,
				ShiftID: MesBasicInfo.ShiftObj.ShiftID,
				WhiteORNight: MesBasicInfo.ShiftObj.ShiftID,
				TestAgainVal: that.testAgainOptions[1].name,
				TestAgain: that.testAgainOptions[1].id,
			};
			that.assignFormData(that.baseFormData, formDefaults);
		},
		onBackPress(options) { // 监听页面返回
			if (options.from == 'navigateBack') { // 通过点击路由返回
				return false;
			} else if (options.from == 'backbutton') { // 通过外置返回
				return true;
			}
		},

		onUnload() {
			uni.$off('refreshDetail');
		},
		methods: {
			handlerTestingNUM(testItem, testIndex) {
				var that = this
				if (testItem.TestingNUM) {
					// TestingNUM
					var reg = /^\d+(?=\.{0,1}\d+$|$)/
					var regFlag = reg.test(testItem.TestingNUM)
					if (regFlag) {
						var testVal = testItem.TestStandardNUM.split('%')[0]
						if (testItem.TestingNUM > testVal) {
							testItem.Testresult = that.TestresultList[0].id
							testItem.TestresultVal = that.TestresultList[0].name
						} else {
							testItem.Testresult = that.TestresultList[1].id
							testItem.TestresultVal = that.TestresultList[1].name
						}
						testItem.TestingNUM = testItem.TestingNUM + '%'
					} else {

						that.showModal('报错', '请输入正确的数值！');
						testItem.TestingNUM = ''
					}
				} else if (!testItem.TestingNUM) {
					testItem.Testresult = ''
					testItem.TestresultVal = ''
				}
				// 统一处理表单默认值
				var formDefaults = {
					ResultVal: '合格',
					Result: 1,
				};
				that.tableData.map((item) => {
					if (item.TestresultVal == '不合格') {
						formDefaults = {
							ResultVal: that.TestresultList[0].name,
							Result: that.TestresultList[0].id
						};
					}
				})
				console.log(that.tableData);
				that.assignFormData(that.baseFormData, formDefaults);
			},
			AddTestAgainVal() {
				var that = this
				that.testAgainShow = true
			},
			//获取重复测量
			testAgainClick(item) {
				console.log(item)
				var that = this
				// 统一处理表单默认值
				const formDefaults = {
					TestAgainVal: item.name,
					TestAgain: item.id,
				};
				that.assignFormData(that.baseFormData, formDefaults);
				that.testAgainShow = false
			},
			// 创建表单赋值工具函数
			assignFormData(target, defaults = {}) {
				var that = this;
				Object.keys(defaults).forEach(key => {
					target[key] = defaults[key];
				});
				that.$forceUpdate();
			},
			async AddModuleData_select(res) {
				try {
					const backDelta = await this.GetModuleData_select(res);
				} catch (error) {
					console.error('返回操作失败:');
				}
			},
			getValue(payload) {
				var that = this;
				console.log(payload);
				that.showMLoading = false
				const {
					type,
					...data
				} = payload;
				if (payload === '返回') return;
				const typeHandlers = {
					'人员': () => ({
						TestName: data.UserName,
					}),
					'产品': () => ({
						ProductName: data.ProductName,
						ProductID: data.ProductID
					}),
					'原材料': () => ({
						ProductName: data.ProductName,
						ProductID: data.ProductID
					}),
				};
				console.log(typeHandlers[type]);
				if (typeHandlers[type]) {
					if (type == '原材料') {
						Object.assign(that.tableData[that.tableDataIndex], typeHandlers[type]());
					} else {
						Object.assign(that.baseFormData, typeHandlers[type]());
						if (type == '产品') {
							that.Request.request('ZS_getMaterialList', {
								ProductID: that.baseFormData.ProductID,
								PageIndex: 1,
								PageSize: 30
							}, function(ret) {
								ret.data.ds.map((item) => {
									item.Remark = item.Remark ? item.Remark : '',
										item.TestStandardNUM = item.TestStandardNUM * 100 + '%'
								})
								Object.assign(that.tableData, that.tableData.concat(ret.data.ds));
								console.log(that.tableData);
							})
						}
					}

				}
				console.log(this.baseFormData);
				this.$forceUpdate()
			},
			modalconfirm() {
				var that = this
				that.modalshow = false
				var parentData
				if (that.modaltitle == '提醒') {
					that.tableData.splice(that.tableDataIndex, 1)
				} else if (that.modaltitle == '提示') {
					var initData = JSON.parse(JSON.stringify(this.$store.state.GuyueModule.ModuleData_select));
					parentData = initData[initData.length - 1]
					that.$refs.framework.ToLevel(parentData)
				}
			},
			showModal(title, content) {
				this.modaltitle = title;
				this.modalcontent = content;
				this.modalshow = true;
			},
			openBaseScreen(str, index) {
				var that = this;
				var obj;
				if (that.ButtonShow == true) {
					if (str == '人员') {
						obj = {
							cmd: 'getEmplByJobName',
							type: str,
							serverSearch: {
								isPaging: true, //是否分页
								pageIndexStr: 'PageIndex', //分页页码字段，应包含在param中		
								searchShow: false, //是否查询
								searchKey: 'searchKey', //搜索关键词，应包含在param中
								showText: 'UserName', //查询结果显示的字段
							},
							param: {
								JobName: '',
								PageIndex: 1,
								PageSize: 30
							}
						}
					} else if (str == '产品') {
						obj = {
							cmd: 'ZS_getProductList',
							type: str,
							serverSearch: {
								isPaging: true, //是否分页
								pageIndexStr: 'PageIndex', //分页页码字段，应包含在param中		
								searchShow: false, //是否查询
								searchKey: 'ProductName', //搜索关键词，应包含在param中
								showText: 'ProductName', //查询结果显示的字段
							},
							param: {
								EquipmentID: that.baseFormData.EquipmentID,
								PageIndex: 1,
								PageSize: 30
							}
						}
					} else if (str == '原材料') {
						console.log(index);
						that.tableDataIndex = index
						console.log(that.tableDataIndex);
						obj = {
							cmd: 'ZS_getMaterialList',
							type: str,
							serverSearch: {
								isPaging: true, //是否分页
								pageIndexStr: 'PageIndex', //分页页码字段，应包含在param中		
								searchShow: false, //是否查询
								searchKey: 'ProductName', //搜索关键词，应包含在param中
								showText: 'ProductName', //查询结果显示的字段
							},
							param: {
								ProductID: that.baseFormData.ProductID,
								PageIndex: 1,
								PageSize: 30
							}
						}
					}

					console.log(obj);
					uni.navigateTo({
						url: `../common/baseScreen?obj=${JSON.stringify(obj)}`,
						animationType: 'slide-in-right',
						animationDuration: 300
					});
				}

			},

			getTarget(arrayName, status) {
				// 1. 根据arrayName获取对应数组
				const targetArray = this[arrayName];
				// 2. 在目标数组中查找
				const obj = targetArray.find(item => item.status === status);
				return obj.name || '';
			},

			queryList(id) {
				var that = this
				try {
					that.Request.request('getWaterContentDetail', {
						ZS_WaterContentID: id
					}, function(ret) {
						that.showMLoading = false
						console.log(ret);
						that.ButtonShow = false

						const [firstItem] = ret.data.ds;
						// that.baseFormData = firstItem
						// console.log(firstItem);
						// console.log(that.baseFormData);
						const formDefaults = {
							StartTime: formatDateTime(firstItem.StartTime),
							ProductName: firstItem.ProductName ?? '',
							ProjectName: firstItem.ProjectName ?? '',
							TestName: firstItem.TestName ?? '',
							ResultVal: that.getTarget('TestresultList', firstItem.Result),
							TestAgainVal: that.getTarget('testAgainOptions', firstItem.TestAgain)
						};
						that.assignFormData(that.baseFormData, formDefaults);
						that.tableData = ret.data.ds1.map(e => ({
							...e,
							Result: e.Result === false ? 0 : 1,
							TestresultVal: that.getTarget('TestresultList', e.Testresult)
						})) || [];
					})
				} catch (e) {
					that.showMLoading = false
					console.log(e)
					this.$utils.hideLoading();
					this.$utils.msg('请求失败请重试')
				}
			},

			changeLevel(list, data, row) {
				getchangeLevel(data)
				uni.$emit('refreshList');
			},

			submit() {
				var that = this
				var msg
				var show = true
				var parentData
				var initData = JSON.parse(JSON.stringify(this.$store.state.GuyueModule.ModuleData_select));



				if (that.baseFormData.ProductName == '' || that.baseFormData.ProductName == null) {
					msg = '请选择产品名称'
					show = false
				}
				that.tableData.some((item, index) => {
					if (item.TestingNUM == '' || item.TestingNUM == null) {
						msg = '请输入实测含水量';
						show = false;
					}
					return false; // 继续遍历下一个
				});
				if (show) {
					var mainObj = {
						EquipmentID: that.baseFormData.EquipmentID,
						ProductCode: that.baseFormData.ProductCode,
						ProductSpec: that.baseFormData.ProductSpec,
						TestName: that.baseFormData.TestName,
						ProductID: that.baseFormData.ProductID,
						StartTime: that.baseFormData.StartTime,
						TestAgain: that.baseFormData.TestAgain,
						WhiteORNight: that.baseFormData.WhiteORNight,

						Result: that.baseFormData.Result
					}
					console.log(mainObj);
					that.Request.request('SaveWaterTest', mainObj, function(mainRes) {
						console.log(mainRes);
						if (mainRes.status == 200) {
							var ID = mainRes.data.ds[0].Column1
							that.tableData.map((item) => {
								var subObj = {
									TestingNUM: item.TestingNUM.split('%')[0] * 100,
									TestStandardNUM: item.TestStandardNUM.split('%')[0] * 100,
									MaterialCode: item.ProductCode,
									Remark: item.Remark,
									Testresult: item.Testresult,
									ZS_WaterContentID: ID,
									Result: that.baseFormData.Result,
									MaterialID: item.ProductID,
								}
								console.log('subObj', JSON.stringify(subObj))
								that.Request.request('SaveWaterTestDel', subObj, function(res) {
									console.log('res', JSON.stringify(res))
									that.$refs.uToast.show({
										title: '保存',
										type: 'success',
										message: '保存成功'
									})
									parentData = initData[initData.length - 1]
									that.$refs.framework.ToLevel(parentData)
								})
							})
						} else {
							that.showModal('报错', mainRes.data.ds[0].msg);
						}
					})
				} else {
					that.showModal('报错', msg);
				}
			},
			// 子表删除
			trash(index) {
				var that = this
				that.tableDataIndex = index
				that.showModal('提醒', '是否删除第' + (index + 1) + '行');
			},


		}
	}
</script>

<style lang="scss">
	@import "../css/index.css";

	.DetailsbottomBtnsTow {
		button {
			margin: 0 5%;
			flex: 1;
		}
	}
</style>